package com.beiyou.servlet;
/**
 * @description
 * @author LittleDesire
 * @date 2022-03-03 周四 19:22
 * @since 17
 */

import com.beiyou.DbUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.UUID;

@WebServlet("/upload")
@MultipartConfig
public class uploadServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        // 获取照片的数据
        Part photo = request.getPart("photo");
        // 获取上传人的姓名
        String name = request.getParameter("user");
        // 截取照片的名字
        String fileName = photo.getSubmittedFileName();
        String sub = fileName.substring(fileName.length() - 4);
        String msg = "";
        if ("".equals(name.trim()) || photo.getSize() == 0) {
            msg = "请上传图片，并且填写上传人姓名";
            request.setAttribute("msg", msg);
        } else {
            // 获取图片的绝对路径
            String path = request.getServletContext().getRealPath("upload");
            File file = new File(path);
            if (!file.exists()) {
                file.mkdirs();
            }
            // 保存图片的名字
            String filename = UUID.randomUUID().toString().toLowerCase();

            // 将图片上传服务器上
            photo.write(file.getAbsolutePath() + "/" + filename + sub);

            DbUtils du = new DbUtils();
            String sql = "insert into t_student(name,ufile,utime,uip) value(?,?,?,inet_aton(?))";
            try {
                PreparedStatement pst = du.getConn().prepareStatement(sql);
                pst.setString(1, name);
                pst.setString(2, filename);
                pst.setTimestamp(3, Timestamp.valueOf(LocalDateTime.now()));
                pst.setString(4, "0:0:0:0:0:0:0:1".equals(request.getRemoteAddr()) ? "192.168.21.4" : request.getRemoteAddr());
                int rows = pst.executeUpdate();
                if (rows > 0) {
                    msg = String.format("上传成功(上传人：%s，文件名：%s，文件大小：%d字节。)", name, fileName, photo.getSize());
                    request.setAttribute("msg", msg);
                } else {
                    msg = "上传失败";
                    request.setAttribute("msg", msg);
                }
                du.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        request.getRequestDispatcher("info.jsp").forward(request, response);
    }
}
